<?php

namespace App\Exceptions;

use App\Support\AliyunSms;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Exception $exception)
    {/*
        if ($this->shouldReport($exception)){
            $aliyunSms = new AliyunSms();
            $aliyunSms->sendExceptionSms(config("site.error_report_phone"), $exception->getMessage());
        }
        */
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Exception
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof TokenInvalidException){
            return response()->json(['code'=>'40001','msg'=>__($exception->getMessage())]);
        }
        return parent::render($request, $exception);
    }
    /**
     * Convert an authentication exception into a response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Auth\AuthenticationException $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        Log::error('sss');
        Log::error($request);

        $logUrl = ''; // route('login');
        if ($request->is(config('prefix.admin'), config('prefix.admin') . '/*')) {
            $logUrl = route('admin.login');
        }

        if ($request->is('api', 'api/*')) {
            Log::error('token is over expired');
            return response()->json(['code' => config('apicode.tokenFail.code'),
                'msg' => __($exception->getMessage()),
                'data' => []
            ]);
        }

        return $request->expectsJson()
            ? response()->json(['message' => $exception->getMessage()], 401)
            : redirect()->guest($logUrl);
    }

    /**
     * @param HttpException $e
     * @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    protected function renderHttpException(HttpExceptionInterface $e)
    {
        $status = $e->getStatusCode();

        $backend = config('prefix.admin');

        // 判断前缀是否是后台
        if ($backend && request()->is($backend, $backend . '/*')) {
            if (view()->exists("backend.errors.{$status}")) {
                return response()->view("backend.errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
            } else {
                return parent::renderHttpException($e);
            }
        } else if (request()->is('api', 'api/*')) {
            Log::error("zz");
            Log::error(__($e->getMessage()));
            return response()->json([
                'code' => config('apicode.tokenFail.code'),
                'msg' => __($e->getMessage()),
                'data' => []
            ]);
        } else {

            if (view()->exists("frontend.errors.{$status}")) {
                return response()->view("frontend.errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
            } else {
                return parent::renderHttpException($e);
            }
        }

    }

    /**
     * Create a response object from the given validation exception.
     *
     * @param \Illuminate\Validation\ValidationException $e
     * @param \Illuminate\Http\Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function convertValidationExceptionToResponse(ValidationException $e, $request)
    {
        if ($e->response) {
            return $e->response;
        }

        if (request()->is('api', 'api/*')) {
            return response()->json([
                'code' => config('apicode.paramError.code'),
                'msg' => config('apicode.paramError.msg'),
                'data' => [],
                'errors' => $e->errors()
            ]);
        }

        return $request->expectsJson()
            ? $this->invalidJson($request, $e)
            : $this->invalid($request, $e);
    }

}
